package huajiu.com.utlis;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;



public class WxJsUtil {
	  public static void main(String[] args) {

	        // 注意 URL 一定要动态获取，不能 hardcode
	        String url = "http://gwchsk.imwork.net/wechat/order/test.html";
	        Map<String, String> ret = sign(url);
	        for (Map.Entry entry : ret.entrySet()) {
	            System.out.println(entry.getKey() + "=" + entry.getValue());
	        }
	    };

	    public static Map<String, String> sign(String url) {
	        Map<String, String> ret = new HashMap<String, String>();
	        //这里的jsapi_ticket是获取的jsapi_ticket。
	        String jsapi_ticket = JSAPITicketTool.getJSApiTicket();
	        String nonce_str = create_nonce_str();
	        String timestamp = create_timestamp();
	        String string1;
	        String signature = "";

	        //注意这里参数名必须全部小写，且必须有序
	        string1 = "jsapi_ticket=" + jsapi_ticket +
	                  "&noncestr=" + nonce_str +
	                  "&timestamp=" + timestamp +
	                  "&url=" + url;
	       // System.out.println(string1);

	        try
	        {
	            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
	            crypt.reset();
	            crypt.update(string1.getBytes("UTF-8"));
	            signature = byteToHex(crypt.digest());
	        }
	        catch (NoSuchAlgorithmException e)
	        {
	            e.printStackTrace();
	        }
	        catch (UnsupportedEncodingException e)
	        {
	            e.printStackTrace();
	        }

	        ret.put("url", url);
	        ret.put("jsapi_ticket", jsapi_ticket);
	        ret.put("nonceStr", nonce_str);
	        ret.put("timestamp", timestamp);
	        ret.put("signature", signature);

	        return ret;
	    }

	    private static String byteToHex(final byte[] hash) {
	        Formatter formatter = new Formatter();
	        for (byte b : hash)
	        {
	            formatter.format("%02x", b);
	        }
	        String result = formatter.toString();
	        formatter.close();
	        return result;
	    }

	    private static String create_nonce_str() {
	        return UUID.randomUUID().toString();
	    }

	    private static String create_timestamp() {
	        return Long.toString(System.currentTimeMillis() / 1000);
	    }
	    public static String getAccess_token(String appid, String appsecret) {

			String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
			String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
			try {
				String result = ServiceUtil.post(requestUrl, new HashMap());
				return result;
			} catch (Exception e) {
				return "";
			}
		}

		public static String getOpen_Access_token(String appid, String appsecret, String code) {

			String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
			String requestUrl = token_url.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);
			try {
				String result = ServiceUtil.post(requestUrl, new HashMap());
				return result;
			} catch (Exception e) {
				return "";
			}
		}

		public static String getOpen_userinfo(String accestoken, String openid) {

			String token_url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
			String requestUrl = token_url.replace("ACCESS_TOKEN", accestoken).replace("OPENID", openid);
			try {
				String result = ServiceUtil.post(requestUrl, new HashMap());
				return result;
			} catch (Exception e) {
				return "";
			}
		}

		public static String getJsApiTicket(String access_token) {
			String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
			String requestUrl = url.replace("ACCESS_TOKEN", access_token);
			try {
				String result = ServiceUtil.post(requestUrl, new HashMap());
				return result;
			} catch (Exception e) {
				return "";
			}

		}

		public static String refresh_token(String appid, String refresh_token) {
			String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
			String requestUrl = url.replace("APPID", appid).replace("REFRESH_TOKEN", refresh_token);
			try {
				String result = ServiceUtil.post(requestUrl, new HashMap());
				return result;
			} catch (Exception e) {
				return "";
			}

		}
		  public static String getNonceStr() {
		        Random random = new Random();
		        return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
		    }
}
